package dataBase;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

@SuppressWarnings("deprecation")
public class DataBaseCommand {
	private Session session;
	private UserManager userManager;
	private FolderManager folManager;
	
	
	public DataBaseCommand() {
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		this.session = sessionFactory.openSession();
		userManager = new UserManager(this.session);
		folManager = new FolderManager(this.session);
	}
	
	public boolean clearDataBase(){
		session.close();
		return true;
	}
	public boolean isUserExist(String userName){
		Query query = session.createQuery("select userName from User where userName='"+userName+"'");
		@SuppressWarnings("unchecked")
		List<User> users = query.list();
		
		if(users.isEmpty())
			return false;//user does not exist
		return true;//user already exist
	}
	
	public boolean addUser(User user){
		user.setPath("c:\\dropbox\\"+user.getUserName()+"\\");
		userManager.saveUser(user);
		session.flush();
		return true;		
	}
	//or maybe change that the function will get the user
	public boolean deleteUser(String userName){
		String hqlDelete = "delete User where userName = :oldName";
		Query findUser = session.createQuery(hqlDelete).setString("oldName",userName);
		@SuppressWarnings("unchecked")
		List <User>list = findUser.list();
		Iterator<User> getUser = list.iterator();
		if(getUser.hasNext()) {
			User user = getUser.next();
			userManager.deleteUser(user);
			session.flush();
			return true;
		}
		return false;
	}
	
	public boolean isFolderExist(String folPath){
		Query query = session.createQuery("select path from Folder where path='"+folPath+"'");
		@SuppressWarnings("unchecked")
		List<Folder> folders = query.list();
		if(folders.isEmpty())
			return false;//folder does not exist
		return true;
	}
	
	public boolean addFolder(User user,Folder fol){
		fol.setPath(user.getPath()+fol.getName()+"\\");
		//need to check if folder exist
		fol.setUserName(user.getUserName());//i'm not sure we need it
		user.getFolders().add(fol);
		userManager.updateUser(user);
		session.flush();
		return true;		
	}
	
	//or maybe change that the function will get the user
	public boolean deleteFolder(User user,Folder fol){
		user.getFolders().remove(fol);
		userManager.updateUser(user);
		session.flush();
		//String hqlDelete = "delete Folder where userName = :oldName";
		//session.createQuery(hqlDelete).setString("oldName",userName).executeUpdate();
		return true;
	}
	//need to continue-but need to know if i can get the user and folder
}
